// 适配所有表格自定义
<template>
  <div class="tableColumnScreenBox">
    <div style="width:51px;height:36px;background: #B7C2CF;border-radius:5px;">
      <a-tooltip title="列设置">
        <a-icon style="margin-left:20px;margin-top:12px" type="setting" @click="()=>{visibleModel=!visibleModel}" class="settingIcon"/>
      </a-tooltip>
    </div>
    <a-modal
      ref="modalRef"
      title="列设置"
      :visible="visibleModel"
      @ok="handleOk"
      @cancel="()=>{visibleModel=!visibleModel}"
      destroyOnClose
    >
      <a-table
        class="mytb"
        :columns="cols"
        :data-source="headerSetData"
        :pagination="false"
        :scroll="{y:300}"
        rowKey="dataIndex"
        >
          <template #show="text,record">
            <a-switch :checked="text" @change="(e) => switchModel(e, record)"/>
          </template>
          <template #soter="text,record,index">
            <div style="float:right">
                <!-- 置顶 -->
              <a-tooltip title="置顶" style="margin-right:5px" v-if="index>0" >
                <a-icon type="vertical-align-top" @click="toTop(record)" />
              </a-tooltip>
              <!-- 上移 -->
              <a-tooltip title="上移" style="margin-right:5px" v-if="index>0" >
                <a-icon type="arrow-up" @click="up(record,index)" />
              </a-tooltip>
              <!-- 下移 -->
              <a-tooltip title="下移" style="margin-right:5px" v-if="headerSetData.length-1>index" >
                <a-icon type="arrow-down" @click="down(record,index)" />
              </a-tooltip>
              <!-- 拖动 -->
              <a-tooltip title="拖动" style="margin-right:5px">
                <a-icon type="menu"/>
              </a-tooltip>
            </div>
          </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script>
import {mapState} from 'vuex'
import Sortable from "sortablejs";
import md5 from 'md5'
export default {
  props: {
    columns: {
      type: Array,
      default: null
    },
  },
  data () {
    return {
      // 代码定义的列数据
      visibleModel:false,
      headerSetData:[
      ],
      cols: [
          {
            title: '序号',
            customRender:(text,record,index)=>`${index+1}`
          },
          {
            title: '字段名称',
            dataIndex: 'title',
          },
          {
            title: '显示/隐藏',
            dataIndex: 'show',
            scopedSlots: { customRender: 'show' }
          },
          {
            title: '排序',
            dataIndex: 'soter',
            scopedSlots: { customRender: 'soter' }
          },
        ]
    }
  },
  watch:{
    visibleModel:{
      handler(val){
        if(val){
          this.getData()
        }
      }
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  mounted(){
  },
  methods: {
    // 设置拖拽
	  setDrag() {
	  // 获取元素
      const el = document.querySelector(".mytb .ant-table-tbody");
      this.sortable = Sortable.create(el, {
        forceFallback:true,
        ghostClass: "sortable-ghost", // Class name for the drop placeholder,
        setData: function (dataTransfer) {
          dataTransfer.setData("Text", "");
        },
        // 拖动结束时回调
        onUpdate: (evt) => {
          const targetRow = this.headerSetData.splice(evt.oldIndex, 1)[0];
          // 更新到表格数据
          this.$nextTick(()=>{
            this.headerSetData.splice(evt.newIndex, 0, targetRow)
          })
        },
      });
    },
    up(record,index){
      if (index != 0) {
        this.headerSetData[index] = this.headerSetData.splice(index - 1, 1, this.headerSetData[index])[0];
      } else {
        this.headerSetData.push(this.headerSetData.shift());
      }
    },
    down(record,index){
      if (index != this.headerSetData.length - 1) {
        this.headerSetData[index] = this.headerSetData.splice(index + 1, 1, this.headerSetData[index])[0];
      } else {
        this.headerSetData.unshift(this.headerSetData.splice(index, 1)[0]);
      }
    },
    toTop(record){
      let oldIndex=0
      if(this.headerSetData.length>0){
        this.headerSetData.forEach((item,index)=>{
          if(item.dataIndex==record.dataIndex){
            oldIndex=index
          }
        })
        this.headerSetData.splice(oldIndex, 1)
        this.headerSetData.unshift(record)
      }
    },
    getData(){
      this.headerSetData=[]
      const colName=JSON.parse(localStorage.getItem(`tf_${this.userInfo.account}_${md5(JSON.stringify(this.columns))}`)) || []
      if(colName.length>0){
        this.headerSetData = colName
      }else{
        this.columns.forEach((item,index)=>{
          if(!item.fixed){
            this.headerSetData.push({
              title:item.title?item.title:item.titleName,
              dataIndex:item.key?item.key:(item.dataIndex?item.dataIndex:item.title),
              show:true,
              order:1,
            })
          }
        })
      }
      this.$nextTick(() => this.setDrag());
    },
    switchModel(e,record){
      record.show=e
    },
    handleOk(){
      // console.log('@@@@@@submit',this.headerSetData)
      this.$emit('handleNewCols',this.headerSetData)
      this.visibleModel=!this.visibleModel
    },
    handleCancel(){
      this.visibleModel=!this.visibleModel
    }
  }
}
</script>
<style lang="less" scoped>
.tableColumnScreenBox {
  width:30px
}
::v-deep .ant-table-row{
  cursor: move;
}
.settingIcon{
  opacity: 0.5;
}
.settingIcon:hover{
  opacity: 1;
}
</style>